package com.featherlike.feather.generator.engine;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.featherlike.feather.generator.config.Constant;
import com.featherlike.framework.common.util.ClassUtil;
import com.featherlike.framework.common.util.Exceptions;
import com.featherlike.framework.common.util.FileUtil;
import com.featherlike.framework.common.util.IOUtil;
import com.featherlike.framework.common.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * @author WYY
 * @description
 */
public class FreeMarkerImpl implements ITemplateEngine {
	private static final Logger logger = LoggerFactory
			.getLogger(VelocityImpl.class);
	private static final Configuration cfg = new Configuration();

	public FreeMarkerImpl(String tmplPath) {
		try {
			if (StringUtil.isEmpty(tmplPath)) {
				cfg.setDirectoryForTemplateLoading(new File(ClassUtil
						.getClassPath()));
			} else {
				cfg.setDirectoryForTemplateLoading(new File(tmplPath));
			}
			cfg.setDefaultEncoding(Constant.ENCODING_UTF8);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 合并模板到文件中
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.featherlike.feather.generator.engine.ITemplateEngine2#
	 * mergeTemplateIntoFile(java.lang.String, java.util.Map, java.lang.String)
	 */
	@Override
	public void mergeTemplateIntoFile(String ftlPath,
			Map<String, Object> model, String filePath) {
		FileWriter writer = null;
		try {
			if (FileUtil.createFile(filePath)) {
				Template template = cfg.getTemplate(ftlPath);
				writer = new FileWriter(filePath);
				template.process(model, writer);
			} else {
				logger.info("文件已存在,生成失败");
			}
		} catch (Exception e) {
			logger.error("合并模板出错！", e);
			throw Exceptions.unchecked(e);
		} finally {
			IOUtil.closeQuietly(writer);
		}
	}

	// 合并模板并返回字符串
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.featherlike.feather.generator.engine.ITemplateEngine2#
	 * mergeTemplateReturnString(java.lang.String, java.util.Map)
	 */
	@Override
	public String mergeTemplateReturnString(String ftlPath,
			Map<String, Object> model) {
		String result;
		StringWriter writer = null;
		try {
			Template template = cfg.getTemplate(ftlPath);
			writer = new StringWriter();
			template.process(model, writer);
			result = writer.toString();
			writer.close();
		} catch (Exception e) {
			logger.error("合并模板出错！", e);
			throw Exceptions.unchecked(e);
		} finally {
			IOUtil.closeQuietly(writer);
		}

		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.featherlike.feather.generator.engine.ITemplateEngine2#getTemplateSuffix
	 * ()
	 */
	@Override
	public String getTemplateSuffix() {
		return Constant.FTL_SURFIX;
	}
}
